package org.opens.javaskill.jvm.classloader;

import org.junit.Test;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Date 2020/10/26 12:38
 * @Created by 99126
 */
public class InitializationPhase {

    private static int x = 10;

    static {
        System.out.println(x);
        x++;
        System.out.println(x);
        y = 300;
        //System.out.println(y);
        System.out.println(SimpleInterface.x);
    }

    private static int y = 20;

    /**
     * 输出:
     * <pre>
     *  t1 LoadClassTest start ...
     * </pre>
     * 说明:
     * <pre>
     *  1. 根据jvm的规范-按需加载, 所以这里jvm启动时并没有去加载LoadClassTest类, 而是创建时采取加载.
     * </pre>
     */
    @Test
    public void test62() {
        new Thread(() -> new LoadClassTest(), "t1").start();
        new Thread(() -> new LoadClassTest(), "t2").start();
    }

}

interface SimpleInterface {

    public static int x = 100;

}

class LoadClassTest {

    private static AtomicBoolean init = new AtomicBoolean(true);

    static {
        System.out.println(Thread.currentThread().getName() + " LoadClassTest start ...");
        while (init.get()) {

        }
        System.out.println("LoadClassTest end ...");
    }

    /**
     * 输出:
     * <pre>
     *  main LoadClassTest start ...
     * </pre>
     * 说明:
     * <pre>
     *  1. 使用main方法运行时, 会先加载当前类, 所以是启动当前main方法的jvm线程触发了去加载当前类.
     * </pre>
     */
    public static void main(String[] args) {
        new Thread(() -> new LoadClassTest(), "t1").start();
        new Thread(() -> new LoadClassTest(), "t2").start();
    }

}